// pages/home/home.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories: ['电子产品', '书籍', '服装', '生活用品', '其他'],
    currentCategory: '',
    products: [],
    leftProducts: [],
    rightProducts: [],
    page: 1,
    loading: false,
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadProducts()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      products: [],
      leftProducts: [],
      rightProducts: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadProducts().then(() => {
        wx.stopPullDownRefresh()
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadProducts()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  async loadProducts() {
    if (this.data.loading || !this.data.hasMore) return

    this.setData({ loading: true })

    try {
      const params = {
        page: this.data.page,
        limit: 10
      }

      if (this.data.currentCategory) {
        params.category = this.data.currentCategory
      }

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/products`,
          method: 'GET',
          data: params,
          success: resolve,
          fail: reject
        })
      })

      console.log('完整的返回数据：', res.data)

      if (res.data.success) {
        const newProducts = res.data.data.products
        const total = res.data.data.total
        const allProducts = [...this.data.products, ...newProducts]

        // 更新瀑布流数据
        const { leftProducts, rightProducts } = this.distributeProducts(allProducts)

        // 计算是否还有更多数据
        const hasMore = allProducts.length < total

        this.setData({
          products: allProducts,
          leftProducts,
          rightProducts,
          page: this.data.page + 1,
          hasMore: hasMore
        })
      }
    } catch (error) {
      console.error('获取商品列表失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 分配商品到两列
  distributeProducts(products) {
    const leftProducts = []
    const rightProducts = []

    products.forEach((product, index) => {
      if (index % 2 === 0) {
        leftProducts.push(product)
      } else {
        rightProducts.push(product)
      }
    })

    return { leftProducts, rightProducts }
  },

  // 切换分类
  switchCategory(e) {
    const category = e.currentTarget.dataset.category
    if (category === this.data.currentCategory) return

    this.setData({
      currentCategory: category,
      products: [],
      leftProducts: [],
      rightProducts: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadProducts()
    })
  },

  // 跳转到搜索页
  goToSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  // 跳转到商品详情
  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product/product?id=${id}`
    })
  }
})